//index.js
//获取应用实例
var app = getApp()
var timer;

Page({
  data: {
    images: {},
    imgurl2: app.urlimg,
    goods_id: '',
    product_id: 0,
    good_num: 1,
    price: null,
    regiment_model: true,
    userInfo: {},
    isAnimation2: false,
    isAnimation1: false,
    isScroll: true,
    selectItem: {},
    actionType: 'cart',
    //  购物数量被选择后改背景色
    isAddNumber: false,
    isReduceNumber: false,
    loadHidden: false,
    loadText: "加载中...",
    goods_thumb: '',
    isScrollTop: true,
    regiment_userid: 0,//开团id
    regiment_share_userid: 0,//
    data2: {
      pintuan: 0,
    },
    content_photo: {},
    defaultpages: 1,
    store_nums: 0,

    //参加的总人数
    user_num: '',
    //已参加人数
    attend_num: '',
    //头像储存
    user: [],
    //倒计时(毫秒数)
    milliseconds: '',
    //倒计时
    time: '',
    //团唯一标识
    teamSign: 0,
    regimentId: 0,
    //判断是否能参团
    isCanJoin: false,
    activity_status:0
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (o) {
    console.log(o);
    console.log(o.id);



    this.setData({
      o: o,
    })
    console.log(o.teamSign);
    if (typeof (o.teamSign) != 'undefined') {
      var str_before = o.teamSign.split('-')[0]
      if (str_before == 'cjt') {
        var notes_title = 1;
      } else if (str_before == 'cjtm') {
        var notes_title = 2;
      }
      this.setData({
        teamSign: o.teamSign,
        notes_title: notes_title,
      });
    }
    if (o.regimentId != 'undefined') {
      this.setData({
        regimentId: o.regimentId
      });
    }
    var regiment_userid = typeof (o.regiment_userid) == 'undefined' ? 0 : o.regiment_userid
    var regiment_share_userid = typeof (o.regiment_share_userid) == 'undefined' ? 0 : o.regiment_share_userid
    //团长id
    if (regiment_userid !== 0) {
      wx.setStorage({
        key: "regiment_userid",
        data: regiment_userid
      })

      wx.setStorage({
        key: "share_goods_id",
        data: o.id
      })

    }
    //分享者id
    if (regiment_share_userid !== 0) {
      wx.setStorage({
        key: "regiment_share_userid",
        data: regiment_share_userid
      })
    }


    var that = this;
    console.log(getCurrentPages())
    wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        var h = res.screenHeight,
          h = h + 'px';
        that.setData({
          goods_id: o.id,
          screenHeight: h,
        })
      }
    })


    app.getUserInfo(function (token_key) {
      var tg = typeof (o.tg) == 'undefined' ? 0 : o.tg
      var regiment_userid = typeof (wx.getStorageSync('regiment_userid')) == 'undefined' ? 0 : wx.getStorageSync('regiment_userid')
      var regiment_share_userid = typeof (wx.getStorageSync('regiment_share_userid')) == 'undefined' ? 0 : wx.getStorageSync('regiment_share_userid')
      wx.request({
        url: app.url + 'api_goods/goods_detailV1',
        data: {
          id: o.id,
          tg: tg,
          regiment_share_userid: regiment_share_userid,
          regiment_userid: regiment_userid,
        },
        header: {
          'content-type': 'application/json',
          'token': token_key
        }, success: function (json) {
          console.log(json);
          if (json.data.done == true) {
            // 抽奖团规则时间
            function getLocalTime(nS) {
              return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
            }

            var start_time = getLocalTime(json.data.result.promotion.start_time);
            var end_time = getLocalTime(json.data.result.promotion.end_time);

            wx.setStorage({
              key: "regiment_userid",
              data: json.data.result.promotion.regiment_userid
            })

            wx.setStorage({
              key: "regiment_share_userid",
              data: json.data.result.promotion.regiment_share_userid
            })

            /*
            return*/
            var spec_array = json.data.result.spec_array
            var spec_title = ''
            if (!spec_array.length > 0) {
              spec_title = '默认属性'
            } else {
              for (var i = 0; i < spec_array.length; i++) {
                if ((spec_array.length - 1) == i) {
                  spec_title += spec_array[i].name
                } else {
                  spec_title += spec_array[i].name + '|'
                }
              }
            }
            json.data.result.spec_title = spec_title
            json.data.result.sell_price = json.data.result.promotion.length > 0 ? '' : '￥' + json.data.result.sell_price

            console.log(json.data.result);
            that.setData({
              data: json.data.result,
              store_nums: json.data.result.store_nums,
              loadHidden: true,
              comment: json.data.result.data,
              content_photo: json.data.result.content,
              start_time: start_time,
              end_time: end_time,
            })
            countdown(that)
            imageForeach(that);
          } else {
            console.log(555)
            //失败
            app.apperror(json)
          }

        }, complete: function () {

        }
      })

      //拼团推荐
      wx.request({
        url: app.url + 'api_team/recommend',
        data: {
          goods_id: o.id,
        },
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token_key')
        },
        success: function (res) {
          console.log(res.data.result);
          that.setData({
            goods_lists: res.data.result,
          })

        },
        // 接口调用失败返回的函数
        fail: function (err) {
          console.log(err)
        }
      })


      //拼团
      wx.request({
        url: app.url + 'api_team/joinGroup',
        data: {
          order_id: o.order_id,
        },
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token_key')
        },
        success: function (res) {
          console.log(res.data.result);

          var goods = res.data.result.goods;
          var num = '';
          var user = [];
          var milliseconds = '';
          var team_sign = '';
          if (goods != undefined) {
            num = goods.team_num - goods.teammen_num;
            milliseconds = goods.pay_time;
            var person = res.data.result.team;
            var mySelf = res.data.result.mySelf;
            var mySelf_else=true;
            for (var i = 0; i < person.length; i++) {
              user.push(person[i]);
              if (person[i].user_id == mySelf) {
                mySelf_else = false;
              }
            }

            var persons = [{ "head_ico": "/pages/icon/packet/shei.png" }];
            for (var i = 0; i < num; i++) {
              user.push(persons[0]);
            }
            //console.log(user);
            that.time(milliseconds);
            team_sign = res.data.result.goods.team_sign;
          }
          that.setData({
            mySelf_else: mySelf_else,
            isCanJoin: res.data.result.isCanJoin,
            activity_status: res.data.result.status,
            user: user,
            user_num: num,
            goods: goods,
            milliseconds: milliseconds,
            teamSign: (o.teamSign) ? o.teamSign : team_sign,
          })

        },
        // 接口调用失败返回的函数
        fail: function (err) {
          console.log(err)
        }
      })

    })



  },
  // 进入商品详情页面(去开团)
  click: function (e) {
    wx.redirectTo({
      url: '../../../pages/group/groupdetail/index?id=' + e.currentTarget.dataset.index + '&regiment_id=' + e.currentTarget.dataset.regiment_id + "&group_type=" + e.currentTarget.dataset.group,
    })
  },
  // 获得毫秒数  转化  成小时、分钟、秒
  time: function (Time) {
    var that = this;
    Time -= 1000;
    var hours = parseInt(Time / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
    if (('' + hours).length == 1) {
      hours = '0' + hours;
    }
    var minutes = parseInt(Time / 1000 / 60 % 60, 10);//计算剩余的分钟 
    if (('' + minutes).length == 1) {
      minutes = '0' + minutes;
    }
    var seconds = parseInt(Time / 1000 % 60, 10);//计算剩余的秒数 
    if (('' + seconds).length == 1) {
      seconds = '0' + seconds;
    }
    var times = hours + ":" + minutes + ":" + seconds;//排列时间

    //console.log(times);
    that.setData({
      time: times,
      milliseconds: Time,
    })
  },

  onReady: function () {

  },

  onHide: function () {
    clearInterval(timer);
  },
  onUnload: function () {
    clearInterval(timer);
  },
  regiment_desc: function () {
    this.setData({
      regiment_model: false,
    })
  },
  modalOk: function () {
    this.setData({
      regiment_model: true,
    })
  },
  onShow: function () {
    //拼团
    var that = this;
    timer = setInterval(function () {
      var new_time = Date.parse(new Date()) / 1000;
      that.setData({
        new_time: new_time,
      })
      // console.log(that.data);
      // console.log(that.data.new_time);
      // console.log(that.data.data.promotion.end_time);
      var time = that.data.milliseconds;
      that.time(time);
    }, 1000);
    // 遍历图片数组
    if (this.data.data == null) return;
    // 秒杀代码
    countdown(this);
  },

  //  响应选择颜色和尺寸
  selectTAP: function () {
    this.setData({
      isAnimation2: true,
    })

    var animation = wx.createAnimation({
      duration: 2000,
      timingFunction: 'ease-in-out'
    })

    this.animation = animation
    var h = "245rpx";
    animation.height(h).translateY(-h).step();
    this.setData({
      animationData: animation.export()
    })
  },
  // 悬浮被单击
  xuanfuTAP: function () {
    var that = this;
    that.setData({
      isAnimation2: false,
      isAnimation1: false,
    })
  },
  manjian: function () {
    this.setData({
      isAnimation1: true
    })
  },
  // 广告图片大小（banner）
  imageLoad: function (e) {
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 718,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 718 / ratio;    //计算的高度值
    var image = this.data.images;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image[e.target.dataset.index] = {
      width: viewWidth,
      height: viewHeight
    }
    this.setData({
      images: image
    })
  },
  // 广告图片（banner）
  swiperItem: function (e) {
    var fid = e.currentTarget.id
    if (e.currentTarget.dataset.url !== '') {
      wx.redirectTo({
        url: e.currentTarget.dataset.url,
      })
    }
  },
  //返回首页
  homeTAP: function () {
    wx.redirectTo(
      {
        url: '/pages/index/index',
        success: function (res) {
          clearInterval(timer);
        }
      }
    )
  },
  //  响应加入购物车
  shopTAP: function (e) {
    this.setData({
      isAnimation2: true,
      actionType: 'cart'
    })

    // 调用动画方法
    moveAnimation(this);
  },

  specTAP: function (e) {
    var that = this
    var py = e.currentTarget.dataset.py
    var spec_array = that.data.data.spec_array
    var value = e.currentTarget.dataset.value
    var spec_detail = that.data.data.spec_detail
    var gobuy = true
    for (var i = 0; i < spec_array.length; i++) {
      if (spec_array[i].py == py) {
        spec_array[i].select = 1
      }
      for (var n = 0; n < spec_array[i].value.length; n++) {
        if (spec_array[i].value[n].value == value) {
          if (typeof (spec_array[i].value[n].img) != 'undefined' && spec_array[i].value[n].img.length > 2) {
            that.setData({ goods_thumb: that.data.imgurl2 + spec_array[i].value[n].img })
          }
          spec_array[i].value[n].select = 1
        } else {
          if (spec_array[i].py == py) {
            spec_array[i].value[n].select = 0
          }
        }
      }
      spec_array[i].value

    }

    var selectItem = ''
    for (var i = 0; i < spec_array.length; i++) {
      if (!spec_array[i].select) {
        gobuy = false
      } else {
        selectItem += spec_array[i].py
      }
      for (var n = 0; n < spec_array[i].value.length; n++) {
        if (spec_array[i].value[n].select == 1) {
          selectItem += spec_array[i].value[n].value
        }
      }
    }

    if (gobuy) {
      var newdata = that.data.data
      newdata.store_nums = 0
      var product_id = 0
      for (var i = 0; i < spec_detail.length; i++) {
        if (spec_detail[i].spec == selectItem) {
          if (typeof (newdata.promotion.price) == 'undefined') {
            newdata.sell_price = spec_detail[i].sell_price
          }
          newdata.store_nums = spec_detail[i].store_nums
          product_id = spec_detail[i].product_id
        }
      }
      that.setData({
        product_id: product_id,
        data: newdata
      })
    }



    that.data.data.spec_array = spec_array
    that.setData({
      data: that.data.data
    })


  }
  ,
  addNum: function (e) {
    var that = this;
    if (that.data.data.promotion.group_type != 2 && that.data.data.promotion.group_type != 3) {
      that.setData({ 'good_num': this.data.good_num + 1 })
    } else {
      wx.showModal({
        title: '提示',
        content: '本商品为优惠商品，每个订单只能购买一件',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
    }
  },
  cutNum: function (e) {
    if (this.data.good_num == 1) {
      return false
    }
    this.setData({ 'good_num': this.data.good_num - 1 })
  },
  // 响应评论
  commentTap: function (e) {
    wx.navigateTo({
      url: '/pages/account/showComment/index?goods_id=' + this.data.goods_id,
      success: function (e) {
      },
      fail: function (e) {
      }
    })

  },
  // 响应触摸增加加数量按钮改变背景色
  addTouchStart: function () {
    this.setData({
      isAddNumber: true,
    })
  },

  // 响应触摸结束增加加数量按钮改变背景色
  addTouchEnd: function () {
    this.setData({
      isAddNumber: false,
    })
  },

  // 响应触摸减少数量按钮改变背景色
  reduceTouchStart: function () {
    this.setData({
      isReduceNumber: true,
    })
  },

  // 响应触摸结束减少数量按钮改变背景色
  reduceTouchEnd: function () {
    this.setData({
      isReduceNumber: false,
    })
  },

  // 响应下一步
  nextStep: function () {
    var that = this
    if (that.data.data.store_nums == 0) {
      wx.showModal({
        title: '提示',
        content: '商品库存不足！',
      })
      return
    }
    if (this.data.goods_id !== '' && this.data.good_num > 0) {
      //如果是点购买的
      if (this.data.actionType == 'buy') {
        wx.request({
          url: app.url + 'api_order/orderDisplay',
          data: {
            goods_id: this.data.goods_id,
            product_id: this.data.product_id,
            number: this.data.good_num,
            pintuan: this.data.data2.pintuan,
          },
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('token_key')

          }, success: function (json) {
            if (json.data.done) {
              wx.navigateTo({
                url: '/pages/index/detail/orderDetail/index?goods_id=' + that.data.goods_id +
                '&product_id=' + that.data.product_id + '&number=' + that.data.good_num + '&actionType=buy'
                + '&pTuan=' + that.data.data2.pintuan + '&tSign=' + that.data.teamSign + '&regiment_id=' + that.data.regimentId,
                success: function (res) {
                  that.setData({
                    isAnimation2: false,
                  })
                }
              })
            } else {
              app.apperror(json);
            }

          }
        })
      } else {
        //如果是点加入购物的api_order/add_cart?goods_id=384&product_id=5033&number=1 
        var taht = this
        wx.request({
          url: app.url + 'api_order/add_cart',
          data: {
            goods_id: taht.data.goods_id,
            product_id: taht.data.product_id,
            number: taht.data.good_num
          },
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('token_key')
          }, success: function (json) {
            if (json.data.done) {
              that.data.data.cart_number = parseInt(that.data.data.cart_number) + parseInt(taht.data.good_num);
              wx.showToast({
                title: '添加购物车成功~',
                icon: 'success',
                duration: 2000
              })
              that.setData({
                isAnimation2: false,
                data: that.data.data
              })
            } else {
              wx.showModal({
                title: '提示',
                content: json.data.message,
              })
            }

          }
        })

      }
    } else {
      wx.showModal({
        title: '提示',
        content: '参数不正常',
      })
    }

  },
  // 响应立即购买
  buyTAP: function (e) {

    this.setData({
      isAnimation2: true,
      actionType: 'buy',
      data2: { pintuan: 0 },
    })
    wx.setStorage({
      key: "pintuan",
      data: '0'
    })
    //  调用动画方法
    moveAnimation(this);



  },
  pintuan: function (e) {
    this.setData({
      isAnimation2: true,
      actionType: 'buy',
      data2: { pintuan: 1 },

    })
    wx.setStorage({
      key: "pintuan",
      data: '1'
    })
    //  调用动画方法
    moveAnimation(this);
  },

  /**
   * 重新开团
   */
  joinGroup: function () {
    var regimentId = this.data.goods.regiment_id;
    var goodsId = this.data.goods.goods_id;
    wx.navigateTo({
      url: '/pages/group/groupdetail/index?id=' + goodsId + "&regiment_id=" + regimentId,
    });
  },




  // 展示图片被单击
  imageTAP: function (e) {
    var current = e.currentTarget.id;

    console.log(current)

    wx.previewImage({
      current: current, // 当前显示图片的链接，不填则默认为 urls 的第一张
      urls: this.data.imgurl,
    })
  },
  goods_thumb: function (e) {
    var src = e.target.dataset.src
    if (src.indexOf("200_200_") != -1) {
      src = src.replace('200_200_', '640_640_');
    }
    var imgarr = [src]
    wx.previewImage({
      current: src, // 当前显示图片的链接，不填则默认为 urls 的第一张
      urls: imgarr,
    })

  }, goods_imgdetail: function (e) {
    var that = this
    var src = e.target.dataset.src
    var imgarr = []
    for (var i = 0; i < that.data.data.content.length; i++) {
      imgarr.push(that.data.imgurl2 + that.data.data.content[i])
    }
    wx.previewImage({
      current: src, // 当前显示图片的链接，不填则默认为 urls 的第一张
      urls: imgarr,
    })

  },
  // cart: function () {

  //   wx.navigateTo(
  //     {
  //       url: '/pages/shop/index',
  // 			success: function (res) {
  // 				clearInterval(timer);
  //       }
  //     })

  //   /*wx.reLaunch(
  //   { 
  //      url: '/pages/shop/index', 
  //          success: function(res){
  // 						clearInterval(timer);
  //        } } )*/


  // },
  // coomodityTAP: function (e) {
  //   wx.redirectTo(
  //     {
  //       url: '/pages/index/detail/index?id=' + e.currentTarget.id,
  // 			success: function (res) {
  // 				clearInterval(timer);
  //       }
  //     }
  //   )
  // },

  onShareAppMessage: function (res) {

    var current = getCurrentPages();
    var idx = current.length-1;
    var path = "/" + current[idx].route + "?";
    path = path + "id=" + current[idx].options['id'] + "&order_id=" + current[idx].options['order_id'];
    var shareText = this.data.goods.shareText;
    return {
      title: "我正在抢" + shareText + "，要不要一起来玩呢?",
      path: path,
      success: function (res) {
        wx.showToast({
          title: '分享成功',
        })
      },
      fail: function (res) {
      }
    }
  },
  toastChange: function () {
    this.setData({ toastHidden: true })
  },
  // 监听滚动事件
  // scrollChange: function (e) {
  //   var that = this;
  //   if (e.detail.scrollTop > 500) {
  //     that.setData({ isScrollTop: false, });
  //   } else {
  //     that.setData({ isScrollTop: true, });
  //   }
  // },

  // 监听返回顶部
  // scrollTop: function (e) {
  //   this.setData({
  //     toTop: 0,
  //     isScrollTop: true,
  //   });

  // },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.onLoad(this.data.o);
    //模拟加载
    setTimeout(function () {
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 1200);
  },

  goodsDetail: function () {
    var current = getCurrentPages();
    var group_type = this.data.data.promotion.group_type;
    wx.navigateTo({
      url: '/pages/group/groupdetail/index?id=' + current[0].options['id'] + "&regiment_id=" +
      current[0].options['regimentId'] + "&group_type=" + group_type
    });
  },
  //查看规则
  go_rule: function () {
    wx.navigateTo({
      url: '/pages/group/rule/index',
      success: function () {
        clearInterval(timer);
      },
    })
  },


  //收集form_id
  submitAct: function (e) {
    wx.request({
      url: app.url + "api_team/collectFormId",
      data: {
        formId: e.detail.formId
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (result) { }
    })
  }


})



/* 秒杀倒计时 */
function countdown(that) {
  var timestamp = Date.parse(new Date());
  timestamp = timestamp / 1000;

  var endTime = that.data.data.promotion.end_time;

  var second = endTime - timestamp;

  var hour = parseInt(second / 3600);
  var minute = second % 3600 / 60;
  minute = parseInt(minute);
  var second2 = second % 3600 % 60 % 60;


  if (second < 0) {
    clearInterval(timer);
    return;
  }
  setTimeout(function () {

    that.setData({
      hour: hour,
      minute: minute,
      second: second2
    });
    countdown(that);
  }
    , 1000)
}

// 动画方法
function moveAnimation(that) {

  var animation = wx.createAnimation({
    duration: 2000,
    timingFunction: 'ease-in-out',
  })

  var h = "auto";
  animation.height(h).translateY(-h).step();
  that.setData({
    animationData: animation.export()
  })
}

// 图片数组重构
function imageForeach(that) {

  var img = that.data.data.photo;
  var url = app.urlimg;
  var imgs = new Array;
  img.forEach(function (e) {
    var imgurl = url + e;
    imgs.push(imgurl);
  })
  that.setData({
    imgurl: imgs,
    goods_thumb: imgs[0],
  })

}